﻿using System;
using System.Linq;
using Pap.Data.Abstraction.Utils;

namespace Pap.Services.Customer
{
    /// <summary>
    /// 
    /// </summary>
    public class OtherCustomerGuarantor : CustomerValidatorBase
    {
        /// <summary>
        /// 
        /// </summary>
        IWorkflowService _WfService;
        /// <summary>
        /// Initializes a new instance of the <see cref="OtherCustomerGuarantor"/> class.
        /// </summary>
        /// <param name="_db">The _DB.</param>
        /// <param name="wfService">The wf service.</param>
        public OtherCustomerGuarantor(IDatabase _db, IWorkflowService wfService)
            : base(_db)
        {
            isError = true;
            canValidateByName = false;
            _WfService = wfService;
        }

        /// <summary>
        /// Validates the specified current committee ID.
        /// </summary>
        /// <param name="currentCommitteeID">The current committee ID.</param>
        /// <param name="customer">The customer.</param>
        /// <returns></returns>
        public override bool Validate(Guid currentCommitteeID, Pap.Data.ICustomer customer)
        {
            int guaranteedCount = (from loan in _database.CustomerLoans
                                   where loan.GuarantorID == customer.CustomerID
                                   select loan.CustomerID).Count();

            if (guaranteedCount > 0)
                return false;
            else
                return true;

            // suggested code
            //var endedLoansIDs = _WfService.GetInStep(Steps.EndedLoans);
            //var guarantorOpendLoans = _database.LoanExecutions.Where(ex => !endedLoansIDs.Contains(ex.LoanID) && ex.GuarantorSSN.Equals(customer.SSN));

            //var executions = from loanEx in guarantorOpendLoans
            //                 let loanAmount = loanEx.TotalLoanAmount
            //                 let alloanPayments = loanEx.LoanExecutionInstallmentsLst.SelectMany(
            //                 inst => inst.LoanInstallmentPaymentLst.Select(payment => payment.PaymentAmount))
            //                 select (alloanPayments.Sum() / loanAmount < .75);

            //if (executions.Any(exec => exec))
            //    return false;
            //else
            //    return true;
        }

        /// <summary>
        /// Validates the specified current committee ID.
        /// </summary>
        /// <param name="currentCommitteeID">The current committee ID.</param>
        /// <param name="customerName">Name of the customer.</param>
        /// <returns></returns>
        public override bool Validate(Guid currentCommitteeID, string customerName)
        {
            throw new Exception("Unsupported. Can't validate for open loan by name only.");
        }
    }
}
